<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card class="box-card">
      <div style="margin-top: 15px;">
        <el-input
          placeholder="请输入内容"
          v-model="formParameters.query"
          class="input-with-select"
          clearable
          @clear="getUserData"
        >
          <el-button
            slot="append"
            icon="el-icon-search"
            @click="getUserData"
          ></el-button>
        </el-input>
        <el-button type="primary" @click="dialogVisible = true"
          >添加用户</el-button
        >
      </div>

      <el-table :data="userData" border style="width: 100%;margin-top:20px;">
        <el-table-column type="index" label="#" width="80"> </el-table-column>
        <el-table-column prop="username" label="姓名" width="180">
        </el-table-column>
        <el-table-column prop="email" label="邮箱" width="230">
        </el-table-column>
        <el-table-column prop="mobile" label="电话" width="230">
        </el-table-column>
        <el-table-column prop="role_name" label="角色" width="180">
        </el-table-column>
        <el-table-column label="状态" width="100">
          <template v-slot="scope">
            <el-switch
              v-model="scope.row.mg_state"
              active-color="#13ce66"
              inactive-color="#ff4949"
              @change="myste(scope.row)"
            >
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template v-slot="scope">
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              @click="modifyUser1(scope.row)"
            ></el-button>
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="delUser(scope.row)"
            ></el-button>
            <el-button
              type="warning"
              icon="el-icon-setting"
              size="mini"
              @click="assignRoles(scope.row)"
            ></el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 分页器 -->
    <div class="block">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="formParameters.pagenum"
        :page-sizes="[2, 6, 8, 10]"
        :page-size="formParameters.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="totals"
      >
      </el-pagination>
    </div>
    <!-- 添加用户弹框 -->

    <el-dialog title="添加用户" :visible.sync="dialogVisible" width="30%">
      <el-form ref="form" :model="userForm" label-width="80px">
        <el-form-item label="用户名">
          <el-input v-model="userForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码">
          <el-input v-model="userForm.password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱">
          <el-input v-model="userForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机号">
          <el-input v-model="userForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUser">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 修改用户弹框 -->

    <el-dialog title="编辑用户" :visible.sync="modifyPopup" width="30%">
      <el-form ref="form" :model="modifyUser" label-width="80px">
        <el-form-item label="用户名">
          <el-input v-model="modifyUser.username" disabled></el-input>
        </el-form-item>

        <el-form-item label="邮箱">
          <el-input v-model="modifyUser.email"></el-input>
        </el-form-item>
        <el-form-item label="手机号">
          <el-input v-model="modifyUser.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="modifyPopup = false">取 消</el-button>
        <el-button type="primary" @click="editUser(modifyUser.id)"
          >确 定</el-button
        >
      </span>
    </el-dialog>
    <!-- 分配权限弹框 -->
    <el-dialog title="分配角色" :visible.sync="jurisdiction" width="30%">
      <p>当前用户：{{ this.assignRolesForm.username }}</p>
      <p>当前角色：{{ this.assignRolesForm.role_name }}</p>
      <el-select v-model="selectId" placeholder="请选择">
        <el-option
          v-for="item in rolesList"
          :key="item.id"
          :label="item.roleName"
          :value="item.id"
        >
        </el-option>
      </el-select>

      <span slot="footer" class="dialog-footer">
        <el-button @click="jurisdiction = false">取 消</el-button>
        <el-button type="primary" @click="determine(assignRolesForm.id)"
          >确 定</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: "",
  // 组件注册
  components: {},
  // 父组件传参
  props: {},
  // 变量声明
  data() {
    return {
      // 控制添加用户弹框显示隐藏
      dialogVisible: false,
      // 控制修改用户弹框显示隐藏
      modifyPopup: false,
      // 控制分配权限弹框显示隐藏
      jurisdiction: false,
      userData: [],
      formParameters: {
        query: "",
        pagenum: 1,
        pagesize: 6,
      },
      //   添加用户的数据
      userForm: {
        username: "",
        password: "",
        email: "",
        mobile: "",
      },
      modifyUser: {
        username: "",
        email: "",
        mobile: "",
        id: "",
      },
      totals: 0,
      assignRolesForm: {
        username: "",
        role_name: "",
        id: "",
      },
      // 下拉框被选中id
      selectId: "",
      rolesList: [],
    };
  },
  // Vue实例创建完成以后执行 数据可用
  created() {
    this.getUserData();
  },
  // Vue模板挂载完毕以后执行  DOM节点加载完毕了（可以获取节点了）
  mounted() {},
  // keepalive 缓存进入执行
  activited() {},
  // vue组件更新完毕以后执行
  update() {},
  // 定义事件
  methods: {
    async getUserData() {
      let res = await this.$axios.get("users", { params: this.formParameters });
      // console.log(res)
      this.totals = res.data.data.total;
      //   console.log(this.totals);
      let { meta } = res.data;
      let { users } = res.data.data;
      // console.log(meta,users)

      if (meta.status == 200) {
        this.userData = users;
        // console.log(this.userdata);
      }
    },
    delUser(item) {
      // console.log(item)
      this.$confirm("此操作将永久删除该文件, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          let res = await this.$axios.delete(`users/${item.id}`);

          let { meta } = res.data;
          //   console.log(meta);

          if (meta.status == 200) {
            this.$message.success(meta.msg);
            this.getUserData();
          } else {
            this.$message.error(meta.msg);
          }
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    handleSizeChange(val) {
      //   console.log(`每页 ${val} 条`);
      this.formParameters.pagesize = val;
      this.getUserData();
    },
    handleCurrentChange(val) {
      //   console.log(`当前页: ${val}`);
      this.formParameters.pagenum = val;
      this.getUserData();
    },
    // 添加用户
    async addUser() {
      let res = await this.$axios.post("users", this.userForm);
      console.log(res);
      let { meta } = res.data;
      if (meta.status == 201) {
        this.$message.success(meta.msg);
        this.getUserData();
        this.dialogVisible = false;
        this.userForm = {};
      } else {
        this.$message.error(meta.msg);
      }
    },
    // 修改赋值
    modifyUser1(item) {
      //   console.log(item);
      this.modifyUser = item;
      // console.log(this.modifyUser)
      this.modifyPopup = true;
      this.getUserData();
    },
    async editUser(id) {
      let res = await this.$axios.put(`users/${id}`, this.modifyUser);
      console.log(res);
      let { meta } = res.data;
      if (meta.status == 200) {
        this.$message.success(meta.msg);
        this.modifyPopup = false;
        this.getUserData();
      } else {
        this.$message.error(meta.msg);
      }
    },
    async myste(item) {
      let res = await this.$axios.put(
        `users/${item.id}/state/${item.mg_state}`
      );
      let { meta } = res.data;
      if (meta.status == 200) {
        this.$message.success(meta.msg);
        this.getUserData();
      } else {
        this.$message.error(meta.msg);
      }
    },
    // 分配角色
    async assignRoles(item) {
      // console.log(item)
      this.assignRolesForm = item;
      const { data: res } = await this.$axios.get("roles");

      this.rolesList = res.data;
      console.log(this.rolesList);
      this.jurisdiction = true;
    },
    async determine(id) {
      console.log(id);
      let res = await this.$axios.put(`users/${id}/role`, {
        rid: this.selectId,
      });
      console.log(res);
      let  { meta } = res.data
      if(meta.status == 200){
        this.$message.success(meta.msg);
        this.jurisdiction = false
      }else{
        this.$message.error(meta.msg);
      }
    },
  },
  // 过滤器
  filter: {},
  // 计算属性
  computed: {},
  // 监听属性
  watch: {},
};
</script>

<style scoped>
.box-card {
  margin: 20px 0 0 0px;
}
.input-with-select {
  width: 400px;
  margin-right: 30px;
}
</style>
